<?php
require_once '../library/Util/Util.php';
class User_Model_Blogs extends Zend_Db_Table{
	protected $_name = 'blogs';
	protected $_primary = 'id';

	
	public function getAllNewBlogs($limit = 15){
		$select = $this->select();
		$select->from(array('b' => $this->_name))
			->limit($limit)
			->order(array('b.created_date DESC'));

		return $this->fetchAll($select)->toArray();		
	}

	public function countAllUserBlogs($uid){
		if (isset($uid) && Util::is_interger($uid) && $uid > 0){
			$select = $this->select();
			$select->from(array('b' => $this->_name), array('count(id) as total'))
				->where('uid = ?', $uid);

			return $this->fetchRow($select)->toArray()['total'];	
		}else{
			return 0;
		}
	}

	public function getUserBlogsInPage($uid, $page = 1, $limit = 15){
		if (isset($uid) && Util::is_interger($uid) && $uid > 0){
			$select = $this->select();
			$select->from(array('b' => $this->_name))
				->where('uid = ?', $uid)
				->limit($limit, ($page-1)*$limit)
				->order(array('b.created_date DESC'));

			return $this->fetchAll($select)->toArray();	
		}else{
			return array();
		}
	}

	public function getBlogById($id){
		if (isset($id) && Util::is_interger($id) && $id > 0){
			$select = $this->select();
			$select->from(array('b' => $this->_name))
				->where('id = ?', $id);

			return $this->fetchAll($select)->toArray();	
		}else{
			return array();
		}		
	}

	public function insertBlog($uid, $title, $content, $image){
		$data = array(	'title' => $title,
						'content' => $content,
						'image' => $image,
						'uid' => $uid,
						'created_date' => time());
		return $this->insert($data);
	}

	public function updateBlog($id, $title, $content, $image){
		$data = array('title' => $title,
					'content' => $content,
					'image' => $image,
					'created_date' => time());

		$where = $this->getAdapter()->quoteInto('id = ?', $id);
		
		return $this->update($data, $where);
	}

	public function deleteBlog($id){
		$where = $this->getAdapter()->quoteInto('id = ?', $id);

		return $this->delete($where);
	}

	public function getTopBlogger($limit = 10){
		$select = $this->select();
		$select->from(array('b' => $this->_name), array('uid', 'COUNT(id) as total'))
				->group('uid')
				->limit($limit)
				->order(array('total DESC'));
			return $this->fetchAll($select)->toArray();			
	}		

}